//
//  APIManager.swift
//  VideoApp
//
//  Created by 连海锋 on 2020/9/10.
//  Copyright © 2020 jbl. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire
import Hue
import QCloudCOSXML

private let apiManager = APIManager()

class APIManager: NSObject {
    
    let request_time_out = 5.0
    let root_url = "http://apitalke.beibeihuiyu.com/api/unified/"
    
    // 登录
    let login_action = "public/login"
    // 获取用户信息
    let user_info_action = "mobile/get-accounts-info"
    // 按层级获取当前登录账号栏目列表
    let category_list_action = "mobile/get-category-list"
    // 按层级获取当前登录账号课件列表
    let course_list_action = "mobile/get-course-list"
    // 获取当前登录账号搜索记录
    let search_history_action = "mobile/get-search-histories"
    // 清空当前登录账号搜索记录
    let search_history_del_action = "mobile/clear-search-histories"
    // 按层级获取当前登录账号课件列表
    let course_detail_action = "mobile/get-course-detail"
    // 获取sourceKey
    let source_key_action = "mobile/get-source-preview-key"
    // 阿里云一键登录
    let at_auth_action = "public/aliyun-token-login"
    // 阿里云一键登录(TV)
    let at_auth_tv_action = "public/aliyun-token-login"
    // 账号密码登录(TV)
    let account_tv_action = "public/aliyun-account-login"
    // 已登录状态扫码登录TV
    let logined_to_login_tv_action = "mobile/transfer-login-device"
    // 获取浏览历史记录
    let history_list_action = "mobile/get-view-logger-list"
    // 修改密码
    let change_password_action = "mobile/account-change-password"
    // 更换用户信息
    let change_user_info_action = "mobile/edit-account-attribute"
    // 获取上传图片OSS信息
    let get_info_from_oss_action = "public/get-cos-credential"
    // 清空所有历史浏览记录
    let clear_all_history_action = "mobile/clear-view-logger"
    
    class var sharedInstance: APIManager {
        return apiManager
    }
}

extension APIManager {
    
    //MARK: - GET/POST 请求
    func sendRequest(urlString: String, method: HTTPMethod, params: JSON?, completion: @escaping (_ response : JSON, _ error : String?) -> Void) {
        let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        let urlStringAll = ((url?.host == nil ? self.root_url: "") + urlString).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        
        // 添加头信息
        var headers:HTTPHeaders = HTTPHeaders.init()
        headers.add(name: "Content-Type", value: "application/json")
        headers.add(name: "Authorization", value: "Bearer "+UserInfo.sharedInstance.token)
        
        print("请求类型：\(method.rawValue), URL:\(String(describing: urlStringAll)), 参数：\(String(describing: params))，Authorization：\(UserInfo.sharedInstance.token)")
        
        AF.request(urlStringAll, method: method, parameters: params?.dictionaryValue, encoder: method == HTTPMethod.post ? JSONParameterEncoder.default : URLEncodedFormParameterEncoder.default, headers: headers, interceptor: nil, requestModifier: { urlRequest in
            urlRequest.timeoutInterval = self.request_time_out
        }).response { response in
            UtilManager.sharedInstance.hideHud()
            switch response.result {
                case .success(let value):
                    let dic = JSON.init(value as Any)
                    print("请求接口：\(urlString) 请求成功:\(dic)")
                    if dic["code"].stringValue != "0000" {
                        completion(dic,dic["message"].stringValue)
                        UtilManager.sharedInstance.getCurrentVc().view.makeToast(dic["msg"].stringValue, duration: 1.0, position: .center)
                        
                        if dic["code"].stringValue == "401" {
                            UserInfo.sharedInstance.clearUserAutoLoginKey()
                            UserInfo.sharedInstance.toLogin("normal")
                        }
                    } else {
                        completion(dic,nil)
                    }
                case .failure(let error):
                    completion(JSON.init(parseJSON: "{}"),error.localizedDescription)
                    UtilManager.sharedInstance.getCurrentVc().view.makeToast("当前无网络，请检查后重试", duration: 1.0, position: .center)
                    print("请求接口：\(urlString) 请求失败:\(error)")
            }
        }
    }
    
    // MARK: - 获取OSS上传文件信息
    func getInfoFromOss(completion : @escaping (_ response : JSON, _ error : String?) -> Void) {
        var params = JSON.init(parseJSON: "{}")
        params["dir"].string = "*"
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.get_info_from_oss_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                completion(result,nil)
            } else {
                completion(result,error)
            }
        }
    }
    
    //MARK: 上传文件
    func uploadFileRequest(fileData: Data, uploadProgress: @escaping (_ progress: Double) -> Void, completion : @escaping (_ response : JSON, _ error : String?) -> Void) {
        
        let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();
        // 存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucket
        put.bucket = AppConfig.sharedInstance.QCloudCOSBucket;
        // 对象键，是对象在 COS 上的完整路径，如果带目录的话，格式为 "video/xxx/movie.mp4"
        put.object = "\(UserInfo.sharedInstance.userAccount)-\(Int(Date().timeIntervalSince1970)).png";
        //需要上传的对象内容。可以传入NSData*或者NSURL*类型的变量
        put.body = fileData as AnyObject

        //监听上传结果
        put.setFinish { (result, error) in
            // 获取上传结果
            if error != nil{
                print("文件上传失败结果：\(error!)");
                completion(JSON.init(""), "\(error!)")
            }else{
                print("文件上传成功结果：\(result!)");
                if result!.callbackResult.status == "200" {
                    completion(JSON.init(result!.location),nil)
                } else {
                    completion(JSON.init(""), "上传失败")
                }
            }
        }

        //监听上传进度
        put.sendProcessBlock = { (bytesSent, totalBytesSent,
            totalBytesExpectedToSend) in
            //      bytesSent                 本次要发送的字节数（一个大文件可能要分多次发送）
            //      totalBytesSent            已发送的字节数
            //      totalBytesExpectedToSend  本次上传要发送的总字节数（即一个文件大小）
            print("Upload Progress: \(totalBytesSent/totalBytesExpectedToSend*100)%")
            uploadProgress(Double(totalBytesSent/totalBytesExpectedToSend))
        };
        //设置上传参数
        put.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in
            //在初始化分块上传完成以后会回调该 block，在这里可以获取 resumeData
            //并且可以通过 resumeData 生成一个分块上传的请求
            let resumeUploadRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>
                .init(request: resumeData as Data?);
        }

        QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
        
    }
    
}
